<?php
class baseapi {

    protected $token;    //令牌
    public $customer_id; //门店公众号用户id
    public $post_data;   //微信服务器发送过来的数据
    public $rule;
    public $replyobj;
    public $resultStr;

    function __construct($token='',$customer_id){
        $this->token = $token;
        $this->customer_id = $customer_id;
    }
    
	//解析微信post过来的数据
    public function getPostData(){
        $postObj = simplexml_load_string($GLOBALS["HTTP_RAW_POST_DATA"], 'SimpleXMLElement', LIBXML_NOCDATA);
        $data = array();
        //通用消息
        $data['FromUserName'] = trim($postObj->FromUserName);
        $data['ToUserName'] = trim($postObj->ToUserName);
        $data['FromMsgType'] = trim($postObj->MsgType);
        $data['Keyword'] = trim($postObj->Content);
        $data['CreateTime'] = trim($postObj->CreateTime);
        //图片消息
        $data['PicUrl'] = trim($postObj->PicUrl);
        //语音消息
        $data['Recognition']  = trim($postObj->Recognition);
        //地理位置消息
        $data['Location_X'] = trim($postObj->Location_X);
        $data['Location_Y'] = trim($postObj->Location_Y);
        $data['Label'] = trim($postObj->Label);
        //事件推送
        $data['Event'] = trim($postObj->Event);
        $data['EventKey'] = trim($postObj->EventKey);
        
        if($data['FromMsgType'] == 'image'){
            $data['Keyword'] = '[发送图片]';
        }elseif($data['FromMsgType'] == 'voice'){
            $data['Keyword'] = $data['Recognition'];
        }elseif($data['FromMsgType'] == 'location'){
            $data['Keyword'] = '[发送位置]'.$data['Label'];
        }elseif($data['Event'] == 'CLICK' || $data['Event'] == 'VIEW'){//菜单点击事件
            $data['Keyword'] = $data['EventKey'];
        }
        
        $data['timesign']=time().rand(1000,9999);
        return $data;
    }
	//回复微信
    public function responseMsg() {
        $this->post_data = $this->getPostData();
		$this->addMessage();//收消息入库
        
        //添加或更新会员
        $Member = D('member');
        $mRow = $Member->where("customer_id='".$this->customer_id."' and fromuser='".$this->post_data['FromUserName']."'")->dataRow();
        
        $rowMem = array();
        $rowMem['customer_id'] = $this->customer_id;
        $rowMem['fromuser']    = $this->post_data['FromUserName'];
        $rowMem['timesign']    = $this->post_data['timesign'];
        
        if(strtolower($this->post_data['Event'])=='unsubscribe'){
            $rowMem['unsubscribe_time']=time();
            $rowMem['status']='0';
        }else{
            if(strtolower($this->post_data['Event'])=='subscribe'){
                $rowMem['subscribe_time']=time();
                $rowMem['status']='1';
            }
            //非取消关注时获取用户头像昵称等信息
            if($this->post_data['FromUserName'] && empty($mRow['nickname'])){
                $configModel=new Model_CustomerConfig();
                $token=$configModel->getToken($this->customer_id);//获取access_token
                $userInfo=$configModel->getUserInfo($token,$this->post_data['FromUserName']);//获取用户基本信息
                if($userInfo['nickname']){
                    $rowMem['group_id'] = $userInfo['groupid'];
                    $rowMem['nickname'] = $userInfo['nickname'];
                    $rowMem['headimgurl'] = $userInfo['headimgurl'];
                    $rowMem['sex'] = $userInfo['sex'];
                    $rowMem['language'] = $userInfo['language'];
                    $rowMem['country'] = $userInfo['country'];
                    $rowMem['province'] = $userInfo['province'];
                    $rowMem['city'] = $userInfo['city'];
                }
            }
        }
        
        if($mRow){
           $Member->updateById($mRow['id'],$rowMem);
        }else{
            $Member->insert($rowMem);
        }
        
        //关注+取消关注
        if(strtolower($this->post_data['Event'])=='subscribe' || strtolower($this->post_data['Event'])=='unsubscribe'){
            //插入关注记录
            $row = array();
            $row['is_care']		= strtolower($this->post_data['Event'])=='subscribe' ? '1' : '0';
            $row['customer_id']	= $this->customer_id;
            $row['fromuser']	= $this->post_data['FromUserName'];
            D('care_record')->insert($row);
            //关注自动回复
            $replyRow = D("auto_reply")->where("customer_id='".$this->customer_id."' and type_id='1' and state='1'")->dataRow();
            if($replyRow){
                if($replyRow['is_keyword']=='1'){
                    $this->post_data['Keyword']=$replyRow['reply_keyword'];
                }else{
                    return $this->create_xmlcontent('text', $replyRow['reply_content']);
                }
            }else{
                return false;
            }
        }
        
		if (strtolower($this->post_data['Event']) != 'location') $returnxml=$this->getInfo();//暂不收录自动上传地理位置的信息
        //file_put_contents('../data/a.txt',$returnxml);
		return $returnxml;
    }
    
	//获取回复内容
	public function getInfo(){
		$KeywordlistModel = new Model_KeywordList();
		$keyword = $this->post_data['Keyword'];
		$keywordinfo = $KeywordlistModel->fetchRow("select * from keyword_list where customer_id='".$this->customer_id."' and keyword = '{$keyword}'");
        
		$base_infoarray = array('text','single','multi','pic','music','video');
		if($keywordinfo['info_type']){
			if(in_array($keywordinfo['info_type'],$base_infoarray)){
				$class='base_info';
			}else{
				$class=$keywordinfo['info_type'].'_info';
			}
			$classFile=$class.'.php';
			
			if(file_exists($classFile)){
				include "$classFile";
				$infoobj = new $class;
				$result['info_id']		= $keywordinfo['info_id'];
				$result['info_type']	= $keywordinfo['info_type'];
				$result['customer_id']	= $this->customer_id;
				$result['fromuser']		= $this->post_data['FromUserName'];
				$result['timesign']		= $this->post_data['timesign'];
				$data= $infoobj->getData($result);
				return $this->create_xmlcontent($data['msgtype'], $data['content'], $data['title'], $data['description'], $data['picurl'], $data['url'], $data['bodystr']);
			}
		}else{
            //无匹配回复
            $replyRow=D("auto_reply")->where("customer_id='".$this->customer_id."' and type_id='2' and state='1'")->dataRow();
            if($replyRow){
                return $this->create_xmlcontent('text', $replyRow['reply_content']);
            }else{
                return false;
            }
		}
	}
    
    //收到的消息入库
    protected function addMessage() {
		$MessageModel = new Model_Message();
        $row = array();
		$row['customer_id']	= $this->customer_id;
		$row['fromuser']	= $this->post_data['FromUserName'];
		$row['touser']		= $this->post_data['ToUserName'];
		$row['msgtype']		= $this->post_data['FromMsgType'];
		$row['msg_content']	= $this->post_data['Keyword'];
		$row['create_time']	= $this->post_data['CreateTime'];
        $MessageModel->insert($row);
    }
    
	/**
     * 组合xml内容 
     * @param string $msgtype text文字,news图文,music音乐
     * @param string $content 文字消息体
     * @param string $title 图文标题
     * @param string $description 图文简介
     * @param string $picurl 图文封面
     * @param string $url 图文链接
     * @param string $bodystr 已组合好的格式体，通常用在多图文中
     */
    public function create_xmlcontent($msgtype,$content='',$title='',$description='',$picurl='',$url='',$bodystr=''){
        if($msgtype == 'text'){
            $content = str_replace("\r","",$content);
            $bodystr = '<Content><![CDATA['.$content.']]></Content>';
        }elseif($msgtype == 'news'){
            $description = cut_str($description, 120, $start= 0, $code = 'UTF-8');
            if ($bodystr == ''){
                $bodystr = "<ArticleCount>1</ArticleCount>
                    <Articles>
                    <item>
                    <Title><![CDATA[$title]]></Title>
                    <Description><![CDATA[$description]]></Description>
                    <PicUrl><![CDATA[$picurl]]></PicUrl>
                    <Url><![CDATA[$url]]></Url>
                    </item>
                    </Articles>";
            }
        }elseif($msgtype == 'music'){
            $bodystr = "<Music>
                <Title><![CDATA[$title]]></Title>
                <Description><![CDATA[$description]]></Description>
                <MusicUrl><![CDATA[$url]]></MusicUrl>
                <HQMusicUrl><![CDATA[$url]]></HQMusicUrl>
                </Music>";
        }
        
        $xmlcontent = "<xml>
            <ToUserName><![CDATA[".$this->post_data['FromUserName']."]]></ToUserName>
            <FromUserName><![CDATA[" . $this->post_data['ToUserName']."]]></FromUserName>
            <CreateTime>".time()."</CreateTime>
            <MsgType><![CDATA[".$msgtype."]]></MsgType>
            ".$bodystr."
            <FuncFlag>0</FuncFlag>
            </xml>";
        return $xmlcontent;
    }
    
    //公众平台校验
    public function valid() {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $tmpArr = array($this->token, $timestamp, $nonce);
        sort($tmpArr,SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return $echoStr;
        }
    }
	
}
?>